import {PageContainer, ProFormSelect, ProFormText, QueryFilter} from '@ant-design/pro-components';
import React, {useEffect, useRef, useState} from 'react';
import {
  listGeneratorVoByPageFastUsingPost,
  listGeneratorVoByPageUsingPost
} from "@/services/backend/generatorController";
import {Avatar, Card, Flex, Image, Input, List, message, Space, Tabs, Tag, Typography} from "antd";
import moment from "moment";
import {UserOutlined} from "@ant-design/icons";
import FileUploader from "@/components/FileUploader";
import {Link} from "umi";

/**
 * 默认分页参数
 */
const DEFAULT_PAGE_PARAMS: PageRequest = {
  current: 1,
  pageSize: 4,
  sortField: 'createTime',
  sortOrder: 'descend',
}

const IndexPage: React.FC = () => {

  const [loading, setLoading] = useState<boolean>(true);
  const [dataList, setDataList] = useState<API.GeneratorVO[]>([]);
  const [total, setTotal] = useState<number>(0);
  /**
   * 搜索条件
   * useState是与状态管理相关的hook，让函数拥有状态。返回固定为长度为2的数组
   * 第一个位置是状态，可以是任何数据类型；第二个位置是用于更新状态的函数
   */
  const [searchParams, setSearchParams] = useState<API.GeneratorQueryRequest>(
    {
      ...DEFAULT_PAGE_PARAMS,
    }
  );

  /**
   * 搜索
   */
  const doSearch: any = async () => {
    setLoading(true);
    try {
      const res = await listGeneratorVoByPageFastUsingPost(searchParams);
      setDataList(res.data?.records ?? []);
      setTotal(Number(res.data?.total) ?? 0); // 后端的long和前端的long精度不同 需要统一
    } catch (error: any) {
      message.error("获取数据失败，" + error.message);
    }
    setLoading(false);
  }

  /**
   * useEffect根据函数和依赖来渲染数据，第一个参数为函数，可以有返回值；
   * 第二个参数为非必填，是个数组，是函数的依赖。它监听并确定函数在本次渲染是否执行
   */
  useEffect(() => {
    doSearch()
  }, [searchParams])

  /**
   * 标签列表
   * @param tags 标签数组，允许为空
   */
  const tagListView = (tags?: string[]) => {
    if (!tags) {
      return <></>;
    }
    return (<div style={{marginBottom: 8}}>{tags.map(tag => (<Tag key={tag}>{tag}</Tag>))}</div>);
  }

  return (
    <PageContainer title={<></>}>
      <Flex justify='center'>
        <Input.Search
          style={{
            width: '50%',
            minWidth: 320,
          }}
          placeholder="请搜索生成器"
          allowClear
          enterButton="搜索"
          size="large"
          onChange={(e) => {
            searchParams.searchText = e.target.value;
          }}
          onSearch={(value: string) => {
            setSearchParams({
              ...DEFAULT_PAGE_PARAMS,
              searchText: value,
            })
          }}
        />
      </Flex>
      <div style={{marginBottom: 16}}/>

      <Tabs
        size='large'
        defaultActiveKey="newest" items=
          {[
            {
              key: 'newest',
              label: '最新',
            },
            {
              key: 'recommend',
              label: '推荐',
            },
          ]}
        onChange={() => {

        }}/>

      <QueryFilter
        defaultCollapsed={false}
        span={12}
        labelWidth="auto"
        labelAlign="left"
        style={{padding: '16px 0'}}
        onFinish={async (values: API.GeneratorQueryRequest) => {
          setSearchParams({
            ...DEFAULT_PAGE_PARAMS,
            // @ts-ignore
            searchText: searchParams.searchText,
            ...values
          })
        }}
      >
        <ProFormSelect label="标签" name="tags" mode="tags"/>
        <ProFormText label="名称" name="name"/>
        <ProFormText name="description" label="描述"/>
      </QueryFilter>

      <div style={{marginBottom: 24}}/>

      <List<API.GeneratorVO>
        rowKey="id"
        loading={loading}
        grid={{
          gutter: 16,
          xs: 1,
          sm: 2,
          md: 3,
          lg: 3,
          xl: 4,
          xxl: 4,
        }}
        dataSource={dataList}
        pagination={{
          current: searchParams.current,
          pageSize: searchParams.pageSize,
          total,
          onChange(current, pageSize) {
            setSearchParams({
              ...searchParams,
              current,
              pageSize
            })
          }
        }}
        renderItem={(data) => (
          <List.Item>
            <Link to={`/generator/detail/${data.id}`}>
              <Card hoverable cover={<Image alt={data.name} src={data.picture}/>}>
                <Card.Meta
                  title={<a>{data.name}</a>}
                  description={
                    <Typography.Paragraph ellipsis={{rows: 2}} style={{height: 44}}>
                      {data.description}
                    </Typography.Paragraph>
                  }
                />
                {tagListView(data.tags)}
                <Flex justify={'space-between'} align={'center'}>
                  <Typography.Paragraph type="secondary" style={{fontSize: 12}}>
                    <span>{moment(data.createTime).fromNow()}</span>
                  </Typography.Paragraph>
                  <div>
                    <Avatar src={data.user?.userAvatar ?? <UserOutlined/>}/>
                  </div>
                </Flex>
              </Card>
            </Link>
          </List.Item>
        )}
      />
    </PageContainer>
  );
};

export default IndexPage;
